package com.iknight.mgr.core.websocket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws/{code}")
public class WebSocketListener {
    private static final Logger logger = LogManager.getLogger(WebSocketListener.class);
    private static ConcurrentHashMap<String, WebSocketDto> websocketMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("code") String code, Session session) {
        if (null == websocketMap.get(code)) {
            logger.info("新加入连接,代码:[" + code + "].");
            WebSocketDto webSocektDto = new WebSocketDto();
            webSocektDto.setCode(code);
            webSocektDto.setSession(session);
            websocketMap.put(code, webSocektDto);
        } else {
            logger.info("已存在连接");
        }
    }

    @OnClose
    public void onClose(@PathParam("code") String code) {
        websocketMap.remove(code);
    }

    @OnMessage
    public void onMessage(String message, Session session) {

    }

    public void onError(Session session, Throwable error) {
        logger.error(error.getMessage());
    }

    public static void sendMessage(String code, String message) {
        if (null == websocketMap || null == websocketMap.get(code)) {
            logger.warn("未检测到有通信通道建立......");
            return;
        } else {
            Session session = websocketMap.get(code).getSession();
            try {
                logger.info(message);
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public static ConcurrentHashMap<String, WebSocketDto> getWebsocketMap() {
        return websocketMap;
    }

    public static void setWebsocketMap(ConcurrentHashMap<String, WebSocketDto> websocketMap) {
        WebSocketListener.websocketMap = websocketMap;
    }
}
